// main.qml
// Qt for HarmonyOS 多线程绘制示例
// 使用两个线程同时绘制圆形和方形

import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Window 2.15
import Multithreading 1.0

ApplicationWindow {
    id: root
    width: Screen.width > 0 ? Math.min(Screen.width * 0.95, 1200) : 1200
    height: Screen.height > 0 ? Math.min(Screen.height * 0.95, 900) : 900
    visible: true
    title: "多线程绘制示例"
    
    // 窗口状态变化时，恢复窗口时将标题栏固定到屏幕顶部
    onVisibilityChanged: {
        if (visibility === Window.Windowed) {
            y = 0
            if (width > Screen.width) {
                width = Screen.width
            }
        }
        // 窗口可见性变化时，延迟重绘 Canvas（确保尺寸已更新）
        if (visibility === Window.Windowed || visibility === Window.Maximized || visibility === Window.FullScreen) {
            Qt.callLater(function() {
                if (canvas.width > 0 && canvas.height > 0) {
                    console.log("Multithreading: 窗口状态变化，强制重绘 Canvas");
                    canvas.requestPaint();
                }
            });
        }
    }
    
    // 窗口状态变化处理
    onWindowStateChanged: {
        console.log("Multithreading: 窗口状态变化 - state:", windowState);
        // 窗口状态变化时，自适应调整绘制
        adaptToWindowSize();
    }
    
    // 圆形点集合
    property var circlePoints: []
    // 方形点集合
    property var squarePoints: []
    
    // 防抖定时器：避免频繁调用自适应调整
    property var adaptTimer: null
    
    // 计算并更新绘制参数（自适应 Canvas 尺寸）
    function updateDrawingParameters() {
        if (canvas.width <= 0 || canvas.height <= 0) {
            console.log("Multithreading: Canvas 尺寸无效，无法更新参数");
            return;
        }
        
        var canvasWidth = canvas.width;
        var canvasHeight = canvas.height;
        
        // 确保参数有效，限制在 Canvas 范围内
        // 圆形半径不超过 Canvas 的 1/3（增大尺寸）
        var maxRadius = Math.min(canvasWidth / 3, canvasHeight / 3);
        var circleRadius = Math.max(20, Math.min(maxRadius, 200)); // 最小20，最大200
        
        // 方形边长不超过 Canvas 的 1/2（增大尺寸）
        var maxSide = Math.min(canvasWidth / 2, canvasHeight / 2);
        var squareSide = Math.max(20, Math.min(maxSide, 200)); // 最小20，最大200
        
        // 计算中心点和起始点，确保在 Canvas 范围内
        // 圆形中心：左侧 1/4 位置，垂直居中
        var circleCenterX = Math.max(circleRadius + 10, Math.min(canvasWidth / 4, canvasWidth - circleRadius - 10));
        var circleCenterY = Math.max(circleRadius + 10, Math.min(canvasHeight / 2, canvasHeight - circleRadius - 10));
        
        // 方形左上角：右侧 3/5 位置，上方 1/5 位置
        var squareTopLeftX = Math.max(10, Math.min(canvasWidth * 3 / 5, canvasWidth - squareSide - 10));
        var squareTopLeftY = Math.max(10, Math.min(canvasHeight / 5, canvasHeight - squareSide - 10));
        
        // 更新线程参数
        circleThread.center = Qt.point(circleCenterX, circleCenterY);
        circleThread.radius = circleRadius;
        
        squareThread.topLeft = Qt.point(squareTopLeftX, squareTopLeftY);
        squareThread.sideLength = squareSide;
        
        console.log("Multithreading: 更新绘制参数 - canvas:", canvasWidth, "x", canvasHeight,
                   "circle center:", circleCenterX, circleCenterY, "radius:", circleRadius,
                   "square topLeft:", squareTopLeftX, squareTopLeftY, "side:", squareSide);
    }
    
    // 自适应调整：窗口尺寸变化时重新绘制（带防抖）
    function adaptToWindowSize() {
        // 如果定时器已存在，先停止
        if (adaptTimer) {
            adaptTimer.stop();
            adaptTimer.destroy();
        }
        
        // 创建新的定时器，延迟执行（防抖：等待尺寸稳定）
        adaptTimer = Qt.createQmlObject('import QtQuick 2.15; Timer { interval: 150; running: true; repeat: false }', root);
        adaptTimer.triggered.connect(function() {
            // 如果正在绘制，先停止
            var wasRunning = circleThread.running || squareThread.running;
            if (wasRunning) {
                console.log("Multithreading: 窗口尺寸变化，停止当前绘制");
                circleThread.stop();
                squareThread.stop();
            }
            
            // 清空当前的点
            circlePoints = [];
            squarePoints = [];
            
            // 延迟更新参数和重绘（确保 Canvas 尺寸已更新）
            Qt.callLater(function() {
                updateDrawingParameters();
                
                // 如果之前正在绘制，重新启动
                if (wasRunning) {
                    console.log("Multithreading: 窗口尺寸变化后，重新启动绘制");
                    circleThread.start();
                    squareThread.start();
                } else {
                    // 即使没有在绘制，也重绘画布（清除旧内容）
                    canvas.requestPaint();
                }
            });
            
            // 清理定时器
            adaptTimer.destroy();
            adaptTimer = null;
        });
    }
    
    // 添加圆形点
    function addCirclePoint(pt) {
        if (!pt) {
            console.log("Multithreading: addCirclePoint 收到空点");
            return;
        }
        // 减少日志输出，每10个点记录一次
        if (circlePoints.length % 10 === 0) {
            console.log("Multithreading: addCirclePoint 收到点:", pt.x, pt.y, "总数:", circlePoints.length + 1);
        }
        var newPoints = circlePoints.slice();
        // QPoint 在 QML 中可以直接使用
        newPoints.push({"x": pt.x, "y": pt.y});
        circlePoints = newPoints;
        
        // 确保 Canvas 已初始化且有有效尺寸
        if (canvas.width > 0 && canvas.height > 0) {
            canvas.requestPaint();
        } else {
            console.log("Multithreading: Canvas 尺寸无效，无法绘制 - width:", canvas.width, "height:", canvas.height);
        }
    }
    
    // 添加方形点
    function addSquarePoint(pt) {
        if (!pt) {
            console.log("Multithreading: addSquarePoint 收到空点");
            return;
        }
        // 减少日志输出，每10个点记录一次
        if (squarePoints.length % 10 === 0) {
            console.log("Multithreading: addSquarePoint 收到点:", pt.x, pt.y, "总数:", squarePoints.length + 1);
        }
        var newPoints = squarePoints.slice();
        // QPoint 在 QML 中可以直接使用
        newPoints.push({"x": pt.x, "y": pt.y});
        squarePoints = newPoints;
        
        // 确保 Canvas 已初始化且有有效尺寸
        if (canvas.width > 0 && canvas.height > 0) {
            canvas.requestPaint();
        } else {
            console.log("Multithreading: Canvas 尺寸无效，无法绘制 - width:", canvas.width, "height:", canvas.height);
        }
    }
    
    Rectangle {
        id: contentRect
        anchors.fill: parent
        color: "#F5F5F5"
        
        ColumnLayout {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            // 标题
            Text {
                Layout.fillWidth: true
                text: "多线程绘制示例"
                font.pixelSize: 48
                font.bold: true
                horizontalAlignment: Text.AlignHCenter
            }
            
            // 画布区域
            Rectangle {
                Layout.fillWidth: true
                Layout.fillHeight: true
                Layout.minimumHeight: 600
                color: "white"
                border.color: "#CCCCCC"
                border.width: 2
                
                Canvas {
                    id: canvas
                    anchors.fill: parent
                    
                    Component.onCompleted: {
                        console.log("Multithreading: Canvas Component.onCompleted - width:", width, "height:", height);
                    }
                    
                    onWidthChanged: {
                        console.log("Multithreading: Canvas width changed to:", width);
                        // Canvas 尺寸变化时，自适应调整绘制
                        if (width > 0 && height > 0) {
                            adaptToWindowSize();
                        }
                    }
                    
                    onHeightChanged: {
                        console.log("Multithreading: Canvas height changed to:", height);
                        // Canvas 尺寸变化时，自适应调整绘制
                        if (width > 0 && height > 0) {
                            adaptToWindowSize();
                        }
                    }
                    
                    onPaint: {
                        console.log("Multithreading: onPaint 被调用 - canvas size:", width, "x", height,
                                    "circlePoints:", circlePoints.length, "squarePoints:", squarePoints.length);
                        
                        // 检查 Canvas 尺寸是否有效
                        if (width <= 0 || height <= 0) {
                            console.log("Multithreading: Canvas 尺寸无效，跳过绘制");
                            return;
                        }
                        
                        var ctx = getContext("2d");
                        if (!ctx) {
                            console.log("Multithreading: 无法获取 Canvas 2D 上下文");
                            return;
                        }
                        
                        // 填充白色背景（防止黑屏）
                        ctx.fillStyle = "white";
                        ctx.fillRect(0, 0, width, height);
                        
                        // 绘制圆形点（蓝色）
                        ctx.strokeStyle = "blue";
                        ctx.lineWidth = 2;
                        if (circlePoints.length > 0) {
                            ctx.beginPath();
                            var pathStarted = false;
                            var validPoints = 0;
                            for (var i = 0; i < circlePoints.length; i++) {
                                var pt = circlePoints[i];
                                // 检查坐标是否在 Canvas 范围内
                                if (pt.x >= 0 && pt.x <= width && pt.y >= 0 && pt.y <= height) {
                                    if (!pathStarted) {
                                        ctx.moveTo(pt.x, pt.y);
                                        pathStarted = true;
                                        validPoints++;
                                        if (i === 0) {
                                            console.log("Multithreading: 绘制圆形起点:", pt.x, pt.y);
                                        }
                                    } else {
                                        ctx.lineTo(pt.x, pt.y);
                                        validPoints++;
                                    }
                                } else {
                                    if (i === 0) {
                                        console.log("Multithreading: 圆形起点超出范围:", pt.x, pt.y, "Canvas:", width, "x", height);
                                    }
                                }
                            }
                            if (pathStarted) {
                                ctx.stroke();
                                console.log("Multithreading: 圆形绘制完成，有效点数:", validPoints, "/", circlePoints.length);
                            } else {
                                console.log("Multithreading: 没有有效的圆形点可以绘制");
                            }
                        }
                        
                        // 绘制方形点（红色）
                        ctx.strokeStyle = "red";
                        ctx.lineWidth = 2;
                        if (squarePoints.length > 0) {
                            ctx.beginPath();
                            var squarePathStarted = false;
                            var validSquarePoints = 0;
                            for (var j = 0; j < squarePoints.length; j++) {
                                var sqPt = squarePoints[j];
                                // 检查坐标是否在 Canvas 范围内
                                if (sqPt.x >= 0 && sqPt.x <= width && sqPt.y >= 0 && sqPt.y <= height) {
                                    if (!squarePathStarted) {
                                        ctx.moveTo(sqPt.x, sqPt.y);
                                        squarePathStarted = true;
                                        validSquarePoints++;
                                        if (j === 0) {
                                            console.log("Multithreading: 绘制方形起点:", sqPt.x, sqPt.y);
                                        }
                                    } else {
                                        ctx.lineTo(sqPt.x, sqPt.y);
                                        validSquarePoints++;
                                    }
                                } else {
                                    if (j === 0) {
                                        console.log("Multithreading: 方形起点超出范围:", sqPt.x, sqPt.y, "Canvas:", width, "x", height);
                                    }
                                }
                            }
                            if (squarePathStarted) {
                                ctx.stroke();
                                console.log("Multithreading: 方形绘制完成，有效点数:", validSquarePoints, "/", squarePoints.length);
                            } else {
                                console.log("Multithreading: 没有有效的方形点可以绘制");
                            }
                        }
                    }
                }
            }
            
            // 控制按钮
            RowLayout {
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignHCenter
                spacing: 20
                
                Button {
                    id: startBtn
                    Layout.preferredWidth: 180
                    Layout.preferredHeight: 60
                    text: "开始绘制"
                    font.pixelSize: 24
                    enabled: !circleThread.running && !squareThread.running
                    onClicked: {
                        console.log("Multithreading: 点击开始绘制按钮");
                        
                        // 确保停止所有可能正在运行的线程
                        if (circleThread.running) {
                            console.log("Multithreading: 停止圆形线程");
                            circleThread.stop();
                        }
                        if (squareThread.running) {
                            console.log("Multithreading: 停止方形线程");
                            squareThread.stop();
                        }
                        
                        // 清空之前的点
                        circlePoints = [];
                        squarePoints = [];
                        canvas.requestPaint();
                        
                        // 更新绘制参数（自适应当前 Canvas 尺寸）
                        updateDrawingParameters();
                        
                        // 等待一小段时间确保线程完全停止，然后启动
                        Qt.callLater(function() {
                            console.log("Multithreading: 启动绘制线程");
                            circleThread.start();
                            squareThread.start();
                        });
                    }
                }
                
                Button {
                    Layout.preferredWidth: 180
                    Layout.preferredHeight: 60
                    text: "停止绘制"
                    font.pixelSize: 24
                    enabled: circleThread.running || squareThread.running
                    onClicked: {
                        circleThread.stop();
                        squareThread.stop();
                    }
                }
                
                Button {
                    Layout.preferredWidth: 180
                    Layout.preferredHeight: 60
                    text: "清空画布"
                    font.pixelSize: 24
                    onClicked: {
                        // 停止所有正在运行的线程
                        if (circleThread.running) {
                            circleThread.stop();
                        }
                        if (squareThread.running) {
                            squareThread.stop();
                        }
                        
                        // 清空点集合
                        circlePoints = [];
                        squarePoints = [];
                        
                        // 重绘画布（显示空白）
                        canvas.requestPaint();
                        
                        console.log("Multithreading: 画布已清空，线程已停止");
                    }
                }
            }
            
            // 状态显示
            Text {
                Layout.fillWidth: true
                text: {
                    var status = "状态: ";
                    if (circleThread.running || squareThread.running) {
                        status += "绘制中...";
                    } else {
                        status += "就绪";
                    }
                    status += "\n圆形点数: " + circlePoints.length;
                    status += " | 方形点数: " + squarePoints.length;
                    return status;
                }
                font.pixelSize: 22
                horizontalAlignment: Text.AlignHCenter
                wrapMode: Text.WordWrap
            }
        }
    }
    
    // 画圆线程
    CircleThread {
        id: circleThread
        onCirclePoint: function(pt) {
            root.addCirclePoint(pt);
        }
        onRunningChanged: {
            console.log("Multithreading: 圆形线程 running 状态变化 - running:", running);
        }
        onFinished: {
            console.log("Multithreading: 画圆线程完成 - running:", running);
        }
    }
    
    // 画方线程
    SquareThread {
        id: squareThread
        onSquarePoint: function(pt) {
            root.addSquarePoint(pt);
        }
        onRunningChanged: {
            console.log("Multithreading: 方形线程 running 状态变化 - running:", running);
        }
        onFinished: {
            console.log("Multithreading: 画方线程完成 - running:", running);
        }
    }
}
